<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
			<el-form-item label="采购编号" prop="purchaseNum">
				<el-input v-model="queryParams.purchaseNum" placeholder="请输入采购编号" clearable size="small" @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="采购名称" prop="purchaseName">
				<el-input v-model="queryParams.purchaseName" placeholder="请输入采购名称" clearable size="small" @keyup.enter.native="handleQuery" />
			</el-form-item>
			<el-form-item label="项目名称" prop="projectId">
				<el-select style="width:160px" v-model="queryParams.projectId" clearable placeholder="请选择项目名称">
					<el-option v-for="item in projectIdOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['business:materialPurchase:add']">新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['business:materialPurchase:edit']">修改</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['business:materialPurchase:remove']">删除</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['business:materialPurchase:export']">导出</el-button>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table v-loading="loading" :data="materialPurchaseList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column label="采购编号" align="center" prop="purchaseNum" />
			<el-table-column label="采购名称" align="center" prop="purchaseName" />
			<el-table-column label="项目名称" align="center" prop="projectName" />
			<el-table-column label="编制人" align="center" prop="organizationName" />
			<el-table-column label="采购开始日期" align="center" prop="purchaseStartDate" width="180">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.purchaseStartDate, '{y}-{m}-{d}') }}</span>
				</template>
			</el-table-column>
			<el-table-column label="采购结束日期" align="center" prop="purchaseEndDate" width="180">
				<template slot-scope="scope">
					<span>{{ parseTime(scope.row.purchaseEndDate, '{y}-{m}-{d}') }}</span>
				</template>
			</el-table-column>
			<el-table-column label="备注" align="center" prop="remark" />
			<el-table-column label="合计" align="center" prop="total" />
			<el-table-column label="大写" align="center" prop="totalWord" />
			<el-table-column label="审批人" align="center" prop="approvalName" />
			<el-table-column label="审批备注" align="center" prop="approvalRemark" />
			<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:materialPurchase:edit']">修改</el-button>
					<el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['business:materialPurchase:remove']">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

		<!-- 添加或修改材料采购申请对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
			<el-form :inline="true" ref="form" :model="form" :rules="rules" label-width="80px">
				<el-form-item label="采购编号" prop="purchaseNum">
					<el-input v-model="form.purchaseNum" placeholder="请输入采购编号" />
				</el-form-item>
				<el-form-item label="采购名称" prop="purchaseName">
					<el-input v-model="form.purchaseName" placeholder="请输入采购名称" />
				</el-form-item>
				<el-form-item label="项目名称" prop="projectId">
					<el-select style="width:185px" v-model="form.projectId" clearable placeholder="请选择项目名称">
						<el-option v-for="item in projectIdOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
					</el-select>
				</el-form-item>
				<!--<el-form-item label="编制人id" prop="organizationId">
					<el-input v-model="form.organizationId" placeholder="请输入编制人id" />
				</el-form-item>
				<el-form-item label="编制人" prop="organizationName">
					<el-input v-model="form.organizationName" placeholder="请输入编制人" />
				</el-form-item>-->
				<el-form-item label="编制人" prop="organizationId">
					<el-select style="width:185px" v-model="form.organizationId" placeholder="请选择用户">
						<el-option v-for="item in userIdOptions" :key="item.userId" :label="item.userName" :value="item.userId"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="开始日期" prop="purchaseStartDate">
					<el-date-picker style="width:185px" clearable size="small" v-model="form.purchaseStartDate" type="date" value-format="yyyy-MM-dd" placeholder="选择开始日期">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="结束日期" prop="purchaseEndDate">
					<el-date-picker style="width:185px" clearable size="small" v-model="form.purchaseEndDate" type="date" value-format="yyyy-MM-dd" placeholder="选择结束日期">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="备注" prop="remark">
					<el-input v-model="form.remark" placeholder="请输入备注" />
				</el-form-item>
				<el-form-item label="审批人" prop="approvalId">
					<el-select style="width:185px" v-model="form.approvalId" placeholder="请选择用户">
						<el-option v-for="item in userIdOptions" :key="item.userId" :label="item.userName" :value="item.userId"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="审批备注" prop="approvalRemark">
					<el-input v-model="form.approvalRemark" placeholder="请输入审批备注" />
				</el-form-item>
				<el-form-item label="合计" prop="total">
					<el-input v-model="form.total" placeholder="请输入合计" />
				</el-form-item>
				<el-form-item label="大写" prop="totalWord">
					<el-input v-model="form.totalWord" placeholder="请输入大写" />
				</el-form-item>
				<el-form-item label="附件" prop="url">
					<el-upload class="upload-demo" ref="uploadRef" :action="upload" highlight-row :headers="headers" :before-upload="beforeUpload" :file-list="fileList" :on-change="onChange" multiple :on-exceed="onExceed" :on-preview="onPreview" :on-remove="onChange">
						<el-button size="small" type="primary">点击上传</el-button>
					</el-upload>
				</el-form-item>
			</el-form>
			<el-table :data="materialPurchaseDetailList">
				<el-table-column label="材料名称" align="center" prop="materialIds">
					<el-cascader size="small" slot-scope="scope" v-model="scope.row.materialIds" :options="materialOptions" :props="{ expandTrigger: 'hover' }" @change="materialNameChange(scope.row)"></el-cascader>
				</el-table-column>
				<el-table-column label="规格" align="center" prop="materialSpec" width="80"/>
				<el-table-column label="单位" align="center" prop="materialUnit" width="80"/>
				<el-table-column label="单价" align="center" prop="unitPrice" width="80"/>
				<el-table-column label="材料数量" align="center" prop="materialNum" width="160">
					<el-input-number size="small" slot-scope="scope" v-model="scope.row.materialNum" placeholder="请输入材料数量" @change="calculation" />
				</el-table-column>
				<el-table-column label="材料单价" align="center" prop="materialUnitPrice" width="160">
					<el-input-number size="small" slot-scope="scope" v-model="scope.row.materialUnitPrice" :step="0.01" placeholder="请输入材料单价" @change="calculation" />
				</el-table-column>
				<el-table-column label="材料备注" align="center" prop="materialRemark" width="160">
					<el-input size="small" slot-scope="scope" v-model="scope.row.materialRemark" placeholder="请输入材料备注" />
				</el-table-column>
				<el-table-column label="小计" align="center" prop="materialSubtotal" />
				</el-table-column>
				<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
					<template slot-scope="scope">
						<el-button size="mini" type="text" icon="el-icon-delete" @click="delMaterialPurchaseDetail(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-table :data="materialPurchaseCarDetailList">
				<el-table-column label="车辆类型" align="center" prop="carType">
					<el-select size="small" slot-scope="scope" v-model="scope.row.carType" placeholder="请选择车辆类型" style="float: left;padding-right: 10px;">
						<el-option v-for="dict in carTypes" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
					</el-select>
				</el-table-column>
				<el-table-column label="车辆型号" align="center" prop="carModel">
					<el-input size="small" slot-scope="scope" v-model="scope.row.carModel" placeholder="请输入车辆型号" />
				</el-table-column>
				<el-table-column label="车辆号码" align="center" prop="carNum">
					<el-input size="small" slot-scope="scope" v-model="scope.row.carNum" placeholder="请输入车辆号码" />
				</el-table-column>
				<el-table-column label="车辆颜色" align="center" prop="carColor">
					<el-input size="small" slot-scope="scope" v-model="scope.row.carColor" placeholder="请输入车辆颜色" />
				</el-table-column>
				<el-table-column label="司机" align="center" prop="driver">
					<el-input size="small" slot-scope="scope" v-model="scope.row.driver" placeholder="请输入司机" />
				</el-table-column>
				<el-table-column label="备注" align="center" prop="remark" width="180">
					<el-input size="small" slot-scope="scope" v-model="scope.row.remark" placeholder="请输入备注" />
				</el-table-column>
				<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
					<template slot-scope="scope">
						<el-button size="mini" type="text" icon="el-icon-delete" @click="delMaterialPurchaseCarDetail(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="addMaterialDetail">添加材料</el-button>
				<el-button type="primary" @click="addCarDetail">添加车辆</el-button>
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import { listMaterialPurchase, getMaterialPurchase, delMaterialPurchase, addMaterialPurchase, updateMaterialPurchase } from "@/api/business/materialPurchase";
	import { listProject } from "@/api/business/project";
	import { numToCapitalization } from '@/utils/guoyuan'
	import { listUser } from "@/api/system/user";
	import { listMaterialPurchaseDetail } from "@/api/business/materialPurchaseDetail";
	import { listMaterialPurchaseCarDetail } from "@/api/business/materialPurchaseCarDetail";
	import { listMaterialLibrary } from "@/api/business/materialLibrary";
	import { upload } from "@/api/system/file";
	import { openMsgs, getHeaders, getFiles, downloadFile } from '@/utils/util';
	import { validatenull, uploadValidate } from '@/utils/validate'
	export default {
		name: "MaterialPurchase",
		components: {},
		data() {
			return {
				loading: true, // 遮罩层
				ids: [], // 选中数组
				single: true, // 非单个禁用
				multiple: true, // 非多个禁用
				showSearch: true, // 显示搜索条件
				total: 0, // 总条数
				materialPurchaseList: [], // 材料采购申请表格数据
				title: "", // 弹出层标题
				open: false, // 是否显示弹出层
				queryParams: { // 查询参数
					pageNum: 1,
					pageSize: 10,
					purchaseNum: null,
					purchaseName: null,
					projectName: null,
				},
				// 表单参数
				form: {},
				// 表单校验
				rules: {},
				projectIdOptions: [],
				userIdOptions: [],
				materialPurchaseDetailList: [],
				materialPurchaseCarDetailList: [],
				openNum: 0,
				carTypes: [],
				fileList: [],
				upload: upload(),
				headers: getHeaders(this), //上传文件头部
			};
		},
		created() {
			this.getList();
			listProject({
				pageNum: 1,
				pageSize: 1000
			}).then(response => {
				this.projectIdOptions = response.rows;
			});
			listUser({
				pageNum: 1,
				pageSize: 1000
			}).then(response => {
				this.userIdOptions = response.rows;
			});
			listMaterialLibrary({
				pageNum: 1,
				pageSize: 1000
			}).then(response => {
				let data = response.rows
				for(let d of data) {
					d.label = d.materialName
					d.value = d.id + ""
				}
				this.materialList = JSON.parse(JSON.stringify(data))
				this.materialOptions = this.handleTree(data, "id");
			});
			this.getDicts("car_type").then(response => {
				this.carTypes = response.data;
			});
		},
		methods: {
			getList() { /** 查询材料采购申请列表 */
				this.loading = true;
				listMaterialPurchase(this.queryParams).then(response => {
					this.materialPurchaseList = response.rows;
					this.total = response.total;
					this.loading = false;
				});
			},
			cancel() { // 取消按钮
				this.open = false;
				this.reset();
			},
			reset() { // 表单重置
				this.form = {
					id: null,
					delFlag: null,
					createBy: null,
					createTime: null,
					updateBy: null,
					updateTime: null,
					purchaseNum: null,
					purchaseName: null,
					projectId: null,
					projectName: null,
					organizationId: null,
					organizationName: null,
					purchaseStartDate: null,
					purchaseEndDate: null,
					remark: null,
					total: null,
					totalWord: null,
					approvalId: null,
					approvalName: null,
					approvalRemark: null,
					url: null
				};
				this.materialPurchaseDetailList = []
				this.materialPurchaseCarDetailList = []
				this.fileList = []
				this.resetForm("form");
			},
			handleQuery() { /** 搜索按钮操作 */
				this.queryParams.pageNum = 1;
				this.getList();
			},
			resetQuery() { /** 重置按钮操作 */
				this.resetForm("queryForm");
				this.handleQuery();
			},
			handleSelectionChange(selection) { // 多选框选中数据
				this.ids = selection.map(item => item.id)
				this.single = selection.length !== 1
				this.multiple = !selection.length
			},
			handleAdd() { /** 新增按钮操作 */
				this.reset();
				this.open = true;
				this.title = "添加材料采购申请";
			},
			handleUpdate(row) { /** 修改按钮操作 */
				this.reset();
				const id = row.id || this.ids
				this.openNum = 0
				getMaterialPurchase(id).then(response => {
					this.form = response.data;
					this.fileList = getFiles(this.form.url)
					this.setOpen()
					this.title = "修改材料采购申请";
					this.getMaterialPurchaseDetail();
					this.getMaterialPurchaseCarDetail();
				});
			},
			submitForm() { /** 提交按钮 */
				this.$refs["form"].validate(valid => {
					if(valid) {
						this.form.projectName = this.getOptionsLabel(this.projectIdOptions, this.form.projectId, 'id', 'name');
						this.form.approvalName = this.getOptionsLabel(this.userIdOptions, this.form.approvalId, 'userId', 'userName');
						this.form.organizationName = this.getOptionsLabel(this.userIdOptions, this.form.organizationId, 'userId', 'userName');
						this.form.materialPurchaseDetailList = this.materialPurchaseDetailList
						this.form.materialPurchaseCarDetailList = this.materialPurchaseCarDetailList
						let url = []
						for(let file of this.fileList) {
							url.push(file.url)
						}
						this.form.url = url.join(",")
						if(this.form.id != null) {
							updateMaterialPurchase(this.form).then(response => {
								this.msgSuccess("修改成功");
								this.open = false;
								this.getList();
							});
						} else {
							addMaterialPurchase(this.form).then(response => {
								this.form.id = response.data
								this.msgSuccess("新增成功");
								this.open = false;
								this.getList();
							});
						}
					}
				});
			},
			getMaterialPurchaseDetail() {
				listMaterialPurchaseDetail({
					pageNum: 1,
					pageSize: 1000,
					materialInOutId: this.form.id
				}).then(response => {
					let data = response.rows
					for(let i in data) {
						data[i].materialIds = data[i].materialId.split(",")
						data[i].key = i + ""
						this.materialNameChange(data[i])
					}
					this.materialPurchaseDetailList = JSON.parse(JSON.stringify(data));
					this.setOpen()
				});
			},
			setOpen() {
				setTimeout(() => {
					this.openNum++
						this.open = this.openNum > 2
				}, 100)
			},
			getMaterialPurchaseCarDetail() {
				listMaterialPurchaseCarDetail({
					pageNum: 1,
					pageSize: 1000,
					materialInOutId: this.form.id
				}).then(response => {
					let data = response.rows
					for(let i in data) {
						data[i].key = i + ""
					}
					this.materialPurchaseCarDetailList = JSON.parse(JSON.stringify(data));
					this.setOpen()
				});
			},
			handleDelete(row) { /** 删除按钮操作 */
				const ids = row.id || this.ids;
				this.$confirm('是否确认删除材料采购申请编号为"' + ids + '"的数据项?', "警告", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				}).then(function() {
					return delMaterialPurchase(ids);
				}).then(() => {
					this.getList();
					this.msgSuccess("删除成功");
				})
			},
			handleExport() { /** 导出按钮操作 */
				this.download('business/materialPurchase/export', {
					...this.queryParams
				}, `材料采购申请.xlsx`)
			},
			addMaterialDetail() {
				this.materialPurchaseDetailList.push({
					key: this.materialPurchaseDetailList.length + "",
					id: null,
					delFlag: null,
					createBy: null,
					createTime: null,
					updateBy: null,
					updateTime: null,
					materialName: null,
					materialNum: null,
					materialUnitPrice: null,
					materialSubtotal: null,
					materialRemark: null,
					materialSpec: null,
					materialUnit: null,
					unitPrice: null,
					materialIds: [],
					materialId: null
				})
			},
			addCarDetail() {
				this.materialPurchaseCarDetailList.push({
					key: this.materialPurchaseCarDetailList.length + "",
					id: null,
					delFlag: null,
					createBy: null,
					createTime: null,
					updateBy: null,
					updateTime: null,
					materialPurchaseId: null,
					carType: null,
					carModel: null,
					carNum: null,
					carColor: null,
					driver: null,
					remark: null
				})
			},
			delMaterialPurchaseDetail(data) {
				let materialPurchaseDetailList = []
				for(let d of this.materialPurchaseDetailList) {
					if(d.key != data.key) {
						materialPurchaseDetailList.push(d)
					}
				}
				this.materialPurchaseDetailList = materialPurchaseDetailList
			},
			delMaterialPurchaseCarDetail(data) {
				let materialPurchaseCarDetailList = []
				for(let d of this.materialPurchaseCarDetailList) {
					if(d.key != data.key) {
						materialPurchaseCarDetailList.push(d)
					}
				}
				this.materialPurchaseCarDetailList = materialPurchaseCarDetailList
			},
			materialNameChange(data) {
				let material = this.getOptions(this.materialList, data.materialIds[data.materialIds.length - 1], 'id');
				data.materialId = data.materialIds.join(",")
				data.materialName = material.materialName
				data.materialSpec = material.materialSpec
				data.materialUnit = material.materialUnit
				data.unitPrice = material.materialUnitPrice
			},
			calculation() {
				let total = 0
				for(let materialPurchaseDetail of this.materialPurchaseDetailList) {
					if(!validatenull(materialPurchaseDetail.materialUnitPrice) && !validatenull(materialPurchaseDetail.materialNum)) {
						materialPurchaseDetail.materialSubtotal = (materialPurchaseDetail.materialNum * materialPurchaseDetail.materialUnitPrice).toFixed(2)
					} else {
						materialPurchaseDetail.materialSubtotal = 0
					}
					total += Number(materialPurchaseDetail.materialSubtotal)
				}
				this.form.total = (total).toFixed(2)
				this.form.totalWord = numToCapitalization(this.form.total)
			},
			beforeUpload(file) { //上传格式
				return uploadValidate(this, file, 'import', '', -1);
			},
			onExceed(files, fileList) {
				openMsgs(this, '', `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`, true, 'warning', 0);
			},
			onChange(file, fileList) {
				let files = []
				if(file.status == "success") {
					for(let f of fileList) {
						files.push({
							"name": f.name,
							"url": validatenull(f.response) ? f.url : f.response.msg
						})
					}
					this.fileList = files
				}
			},
			onPreview(file) {
				downloadFile(file)
			},
		}
	};
</script>